/**
 * Project Name:MyTookit
 * Package Name:com.xuwei.utils.db
 * author:David
 * Date:2016年6月1日下午3:34:34
 * Copyright (c) 2016, xw123box@126.com All Rights Reserved.
 *
 */
package com.xuwei.utils.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 数据库操作工具类
 * @author David
 * @since 2016年6月1日 下午3:34:34
 * @version 
 * @since JDK 1.6
 */
public class DbUtil {
	private static final String MYSQL = "jdbc:mysql://";
	private static final String ORACLE = "jdbc:oracle:thin:@";
	private static final String SQLSERVER = "jdbc:microsoft:sqlserver://";
	
	/**
	 * 获得数据库连接
	 * @param DBType 数据库类型
	 * @param url  
	 * @param user
	 * @param password
	 * @return
	 */
	public static Connection getConnection(String DBType, String url, 
			String user, String password){
		if("mysql".equalsIgnoreCase(DBType)){
			return getMySqlConn(url, user, password);
		}
		if("oracle".equalsIgnoreCase(DBType)){
			return getOracleConn(url, user, password);
		}
		if("sqlserver".equals(DBType)){
			return getSqlServerConn(url, user, password);
		}
		return null;
	}
	
	/**
	 * 关闭连接
	 * @param conn
	 */
	public static void closeConn(Connection conn){
		if(conn!=null){
			try{
				conn.close();
			}catch(SQLException e){
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 获取mysql数据库连接
	 * @param url
	 * @param user
	 * @param password
	 * @return
	 */
	private static Connection getMySqlConn(String url, String user,
			String password){
		Connection conn = null;
		try{
			Class.forName("com.mysql.jdbc.Driver");//load driver
			conn = DriverManager.getConnection(MYSQL+url, user, password);
		}catch(ClassNotFoundException e){
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	/**
	 * 获取oracle数据库连接
	 * @param url
	 * @param user
	 * @param password
	 * @return
	 */
	private static Connection getOracleConn(String url, String user,
			String password) {
		Connection conn = null;
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");// 加载驱动
			conn = DriverManager.getConnection(ORACLE + url, "scott", "tiger");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	/**
	 * 获取sqlserver数据库连接
	 * @param url
	 * @param user
	 * @param password
	 * @return
	 */
	private static Connection getSqlServerConn(String url, String user,
			String password) {
		Connection conn = null;
		try {
			Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");// 加载驱动
			conn = DriverManager.getConnection(SQLSERVER + url, "root", "root");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	
}
